<?php 
    namespace Application\Component;
    use Doctrine\ORM\EntityManager;
    use Application\Entity\Comment;
    use DateTime;
    use Application\Component\AbstractComponent;
    
    class CommentComponent extends AbstractComponent {
        protected  $entity="Application\\Entity\\Comment";
        
        
        function insert($object){
            $now = new DateTime("now");
            $object->createdAt = $now;
            $object->modifiedAt = $now;
            $this->em->persist($object);
            $this->em->flush();
        }
        
        
        function update($object){
            $now = new DateTime("now");
            $object->modifiedAt = $now;
            $this->em->persist($object);
            $this->em->flush();
        }
        
        
        function delete($id){
            $user = $this->em->find($this->entity, $id);
            $this->em->remove($user);
            $this->em->flush();
        }
        
        
        function get($id){
            return $this->em->find($this->entity, $id);
        }

        
        function listAll(){
            return $this->em->getRepository($this->entity)->findAll();
        }
        
        public function getLastResponseComment($comment){
            if($comment->responseComment==null) return null;
            $response = $this->get($comment->responseComment->id);
            return $this->getLastNextComment($response);
        }
        
        public function getLastNextComment($comment){
            $result = $comment;
            while($result!=null){
                if($result->nextComment==null) return $result;
                $result = $result->nextComment;
            }
            return null;
        }
        
        public function getByNextCommentId($nextCommentId,$number = 30){
            return $this->em->getRepository($this->entity)->getByNextCommentId($nextCommentId,$number = 30);
        }
        
        
        public function getByPreviousCommentId($previousCommentId,$number = 30){
            return $this->em->getRepository($this->entity)->getByPreviousCommentId($previousCommentId,$number = 30);
        }
        
        
        public function getByResponseCommentId($responseCommentId,$number = 30){
            return $this->em->getRepository($this->entity)->getByResponseCommentId($responseCommentId,$number = 30);
        }
        
        
    }
